﻿using HospitalSalarySystem.Models;
using HospitalSalarySystem.Repositories;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;

namespace HospitalSalarySystem.Forms
{
    public partial class ImportForm : Form
    {
        private readonly EmployeeRepository _repository;
        private BackgroundWorker _bgWorker;
        private int _totalRecords;
        private int _successCount;
        public int SuccessCount { get => _successCount; set => _successCount = value; }
        private int _errorCount;
        private List<string> _errorMessages = new List<string>();


        public ImportForm()
        {
            InitializeComponent();
            _repository = new EmployeeRepository("employees.db");
            InitializeBackgroundWorker();
        }

        private void ImportForm_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Copy;
        }

        private void ImportForm_DragDrop(object sender, DragEventArgs e)
        {
            var files = (string[])e.Data.GetData(DataFormats.FileDrop);
            if (files.Length > 0)
            {
                txtFilePath.Text = files[0];
                btnImport.Enabled = true;
            }
        }
        /// <summary>
        /// 初始化后台工作线程
        /// </summary>
        private void InitializeBackgroundWorker()
        {
            _bgWorker = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

            _bgWorker.DoWork += BgWorker_DoWork;
            _bgWorker.ProgressChanged += BgWorker_ProgressChanged;
            _bgWorker.RunWorkerCompleted += BgWorker_RunWorkerCompleted;
        }

        /// <summary>
        /// 选择文件按钮点击事件
        /// </summary>
        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            using (var openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "CSV文件|*.csv|所有文件|*.*";
                openFileDialog.Title = "选择要导入的员工数据文件";

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtFilePath.Text = openFileDialog.FileName;
                    btnImport.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 开始导入按钮点击事件
        /// </summary>
        private void btnImport_Click(object sender, EventArgs e)
        {
            if (!File.Exists(txtFilePath.Text))
            {
                MessageBox.Show("文件不存在，请重新选择", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnImport.Enabled = false;
            btnSelectFile.Enabled = false;
            progressBar.Value = 0;
            _errorMessages.Clear();

            // 开始后台任务
            _bgWorker.RunWorkerAsync(txtFilePath.Text);
        }

        /// <summary>
        /// 后台工作主逻辑
        /// </summary>
        private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            var filePath = e.Argument as string;
            var employees = new List<Employee>();

            try
            {
                using (var db = new LiteDB.LiteDatabase("employees.db"))
                    if (db.BeginTrans() == true)
                    {
                        var col = db.GetCollection<Employee>("employees");
                        var lines = (string[])File.ReadAllLines(filePath, System.Text.Encoding.UTF8);
                        _totalRecords = 0;

                        foreach (var line in lines)
                        {
                            if (_bgWorker.CancellationPending)
                            {
                                e.Cancel = true;
                                return;
                            }

                            // 跳过标题行
                            if (_totalRecords++ == 0) continue;

                            try
                            {
                                var employee = ParseCsvLine(line);
                                col.Insert(employee);
                                SuccessCount++;
                            }
                            catch (Exception ex)
                            {
                                _errorCount++;
                                _errorMessages.Add($"第{_totalRecords}行错误：{ex.Message}");
                            }

                            // 每处理10条更新一次进度
                            if (_totalRecords % 10 == 0)
                            {
                                _bgWorker.ReportProgress((int)(_totalRecords * 100 / (double)(lines.Length)));
                            }
                        }

                        db.Commit();
                    }
            }
            catch (Exception ex)
            {
                _errorMessages.Add($"系统错误：{ex.Message}");
            }
        }

        /// <summary>
        /// 解析单行CSV数据
        /// </summary>
        private Employee ParseCsvLine(string line)
        {
            var columns = line.Split(',');

            if (columns.Length < 12)
                throw new FormatException("字段数量不足");

            return new Employee
            {
                Name = columns[0].Trim(),
                AppointmentDate = ParseDate(columns[1], "任职时间"),
                BirthDate = ParseDate(columns[2], "出生年月"),
                EnrollmentDate = ParseDate(columns[3], "入伍年月"),
                Education = ValidateRequired(columns[4], "学历"),
                Qualification = columns[5].Trim(),
                ConfirmationDate = ParseDate(columns[6], "确认时间"),
                CurrentTitle = ValidateRequired(columns[7], "现聘职称"),
                FirstHireDate = ParseDate(columns[8], "首聘时间"),
                RenewalDate = ParseDate(columns[9], "续聘时间"),
                PositionLevel = ValidateRequired(columns[10], "岗位等级"),
                IsNurse = ParseBool(columns[11]),
                Remarks = columns.Length > 12 ? columns[12].Trim() : "",
                JintTieLevel = ValidateRequired(columns[13], "津贴职级"),
                XinJiLevel = ParseInt(columns[14], "薪级"),
                Bili = ParseDecimal(columns[15], "比例")
            };
        }


        /// <summary>
        /// 解析Int字段
        /// </summary>
        private int ParseInt(string value, string fieldName)
        {
            if (int.TryParse(value, out int result))
                return result;

            throw new FormatException($"{fieldName}格式不正确");
        }
        /// <summary>
        /// 解析Double字段
        /// </summary>
        private decimal ParseDecimal(string value, string fieldName)
        {
            if (decimal.TryParse(value, out decimal result))
                return result;

            throw new FormatException($"{fieldName}格式不正确");
        }


        /// <summary>
        /// 解析日期字段
        /// </summary>
        private DateTime ParseDate(string value, string fieldName)
        {
            if (DateTime.TryParse(value, out DateTime result))
                return result;
            else
                return DateTime.MinValue;

            throw new FormatException($"{fieldName}格式不正确");
        }

        /// <summary>
        /// 验证必填字段
        /// </summary>
        private string ValidateRequired(string value, string fieldName)
        {
            if (string.IsNullOrWhiteSpace(value))
                throw new FormatException($"{fieldName}不能为空");

            return value.Trim();
        }

        /// <summary>
        /// 解析布尔值
        /// </summary>
        private bool ParseBool(string value)
        {
            return value.Trim().ToLower() switch
            {
                "true" => true,
                "1" => true,
                _ => false
            };
        }

        /// <summary>
        /// 进度更新处理
        /// </summary>
        private void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar.Value = e.ProgressPercentage;
            lblProgress.Text = $"正在处理：{e.ProgressPercentage}%";
        }

        /// <summary>
        /// 导入完成处理
        /// </summary>
        private void BgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnImport.Enabled = true;
            btnSelectFile.Enabled = true;

            var message = $"导入完成\n成功：{SuccessCount}条\n失败：{_errorCount}条";

            if (_errorCount > 0)
            {
                message += $"\n错误详情已保存到：{SaveErrorLog()}";
            }

            MessageBox.Show(message, "导入结果",
                MessageBoxButtons.OK,
                _errorCount > 0 ? MessageBoxIcon.Warning : MessageBoxIcon.Information);

            if (e.Error != null)
            {
                MessageBox.Show($"发生未处理异常：{e.Error.Message}", "系统错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            if (SuccessCount > 0)
            {
                DialogResult = DialogResult.OK;
            }
        }

        /// <summary>
        /// 保存错误日志到临时文件
        /// </summary>
        private string SaveErrorLog()
        {
            var tempPath = Path.GetTempFileName();
            File.WriteAllLines(tempPath, _errorMessages);
            return tempPath;
        }

        /// <summary>
        /// 窗体关闭时取消后台任务
        /// </summary>
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (_bgWorker.IsBusy)
            {
                _bgWorker.CancelAsync();
                MessageBox.Show("正在停止导入任务...", "提示",
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                e.Cancel = true;
            }
            base.OnFormClosing(e);
        }
    }
}